package com.north.light.libpicselect.ui;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.recyclerview.widget.GridLayoutManager;

import com.north.light.libpicselect.PicSelMain;
import com.north.light.libpicselect.PicSelParamsBuilder;
import com.north.light.libpicselect.R;
import com.north.light.libpicselect.adapter.LibPicSelAdapter;
import com.north.light.libpicselect.bean.LibPicDirecotryIntentInfo;
import com.north.light.libpicselect.bean.LibPicInfo;
import com.north.light.libpicselect.bean.LibPicSelIntentInfo;
import com.north.light.libpicselect.constant.LibPicIntentCode;
import com.north.light.libpicselect.databus.LibPicDataBusManager;
import com.north.light.libpicselect.model.LibPicSelConfig;
import com.north.light.libpicselect.model.LibPicSelectApi;
import com.north.light.libpicselect.model.LibPicSelectManager;
import com.north.light.libpicselect.utils.LibPicCloneUtils;
import com.north.light.libpicselect.utils.LibPicToastUtils;
import com.north.light.libpicselect.widget.recyclerview.LibPicRecyclerView;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 需要注意由于对象引用，导致数据错乱问题
 * change by lzt 20200823 增加视频显示逻辑
 * change by lzt 20220404 增加自定义视频播放intent参数
 * change by lzt 修改当点击拍照的时候，弹出窗口，
 */
public class LibPicSelectActivity extends LibPicBaseActivity {

    private int mLimit = 9;

    private final int REQUEST_DIR_CODE = 0x1001;//目录页面request

    private LibPicRecyclerView mRecyContent;
    private LibPicSelAdapter mAdapter;

    private ImageView mBack;//返回
    private TextView mTitle;//标题
    private TextView mConfirm;//确定
    private TextView mCancel;//取消
    private TextView mPreview;//预览

    private Map<String, List<LibPicInfo>> mFilterData = new HashMap<>();//已经分类好的数据

    private boolean isShowCamera;//是否显示相机图标
    private boolean isShowGif;//显示gif标识
    private boolean isShowVideo;//显示视频标识
    //1系统默认拍照 2使用图片自带的拍照 3使用开发者自定义的拍照
    private int isCusCameraMode;
    //1系统默认播放 2使用图片自带的播放 3使用开发者自定义的播放
    private int mCusVideoPlayUIMode = 1;
    //传入的具体配置参数
    private PicSelParamsBuilder mParamsBuilder = new PicSelParamsBuilder();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        getIntentData();
        super.onCreate(savedInstanceState);
        //根据theme--初始化布局
        int themeMode = mParamsBuilder.getTheme();
        if (themeMode == 1) {
            setContentView(R.layout.lib_pic_activity_pic_select_light);
        } else {
            //默认黑色
            setContentView(R.layout.lib_pic_activity_pic_select);
        }
        initView();
        initData();
    }

    private void getIntentData() {
        if (getIntent() != null) {
            mLimit = getIntent().getIntExtra(LibPicIntentCode.PIC_SEL_DATA_LIMIT, 9);//默认为九个
            isShowCamera = getIntent().getBooleanExtra(LibPicIntentCode.PIC_SEL_DATA_NEED_CAMERA, false);//相机显示标识
            isShowGif = getIntent().getBooleanExtra(LibPicIntentCode.PIC_SEL_DATA_SHOW_GIF, false);//gif显示标识
            isShowVideo = getIntent().getBooleanExtra(LibPicIntentCode.PIC_SEL_DATA_SHOW_VIDEO, false);//视频显示标识
            isCusCameraMode = getIntent().getIntExtra(LibPicIntentCode.PIC_SEL_DATA_CUS_CAMERA, 1);//自定义相机标识
            mCusVideoPlayUIMode = getIntent().getIntExtra(LibPicIntentCode.PIC_SEL_DATA_CUS_VIDEO_PLAYER, 1);//自定义视频播放界面
            if (getIntent().getSerializableExtra(LibPicIntentCode.PIC_SEL_DATA_PARAMS) != null) {
                mParamsBuilder = (PicSelParamsBuilder) getIntent().getSerializableExtra(LibPicIntentCode.PIC_SEL_DATA_PARAMS);
            } else {
                mParamsBuilder = new PicSelParamsBuilder();
            }
        }
    }

    private void initView() {
        //限制的数量，也要加上已经选中的图片数量
        mLimit = (mLimit + mParamsBuilder.getSelPicList().size());
        if (mLimit > 9) mLimit = 9;
        mRecyContent = findViewById(R.id.lib_pic_activity_pic_sel_recy);
        mBack = findViewById(R.id.lib_pic_activity_pic_sel_back);
        mTitle = findViewById(R.id.lib_pic_activity_pic_sel_title);
        mConfirm = findViewById(R.id.lib_pic_activity_pic_sel_confirm);
        mCancel = findViewById(R.id.lib_pic_activity_pic_sel_cancel);
        mPreview = findViewById(R.id.lib_pic_activity_pic_sel_preview);

        mRecyContent.setLayoutManager(new GridLayoutManager(this, 4));
        mAdapter = new LibPicSelAdapter(this, isShowCamera);
        mAdapter.setParams(mParamsBuilder);
        mAdapter.setSelectLimit(mLimit);
        mRecyContent.setAdapter(mAdapter);
        //设置初始值
        updateSelCount();
    }

    private void initData() {
        //预览数据
        mPreview.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //预览，即获取选中的数据，进行预览
                if (mAdapter == null) {
                    return;
                }
                List<LibPicInfo> selectedInfo = mAdapter.getSelectPicInfo();
                if (selectedInfo == null || selectedInfo.size() == 0) {
                    LibPicToastUtils.toast(LibPicSelectActivity.this, getString(R.string.lib_pic_activity_sel_please_sel_pic), Toast.LENGTH_SHORT);
                    return;
                }
                List<String> result = new ArrayList<>();
                List<LibPicInfo> local = LibPicCloneUtils.cloneObjectSer(selectedInfo);
                for (LibPicInfo cache : selectedInfo) {
                    result.add(cache.getPath());
                }
                //赋值对象到内存中
                LibPicSelIntentInfo.getInstance().setPicSelList(local);
                LibPicSelIntentInfo.getInstance().setPicList(result);
                LibPicBrowserActivity.launchPreView(LibPicSelectActivity.this, 0,
                        mLimit, mCusVideoPlayUIMode, mParamsBuilder);
            }
        });
        //结束页面
        mBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                LibPicDataBusManager.getInstance().cancel();
                finish();
            }
        });
        mCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                LibPicDataBusManager.getInstance().cancel();
                finish();
            }
        });
        //确定回调
        mConfirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mAdapter == null) {
                    return;
                }
                List<String> selInfo = mAdapter.getSelectInfo();
                if (selInfo == null || selInfo.size() == 0) {
                    LibPicToastUtils.toast(LibPicSelectActivity.this, getString(R.string.lib_pic_activity_sel_please_sel_pic), Toast.LENGTH_SHORT);
                    return;
                }
                Intent result = new Intent();
                result.putExtra(LibPicIntentCode.PIC_SEL_DATA_SELECT, (Serializable) selInfo);
                setResult(LibPicIntentCode.PIC_SEL_RES, result);
                finish();
            }
        });
        mTitle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mFilterData == null || mFilterData.size() == 0) {
                    LibPicToastUtils.toast(LibPicSelectActivity.this.getApplicationContext(), getString(R.string.lib_pic_data_error), Toast.LENGTH_SHORT);
                } else {
                    //打开列表__数据太大，设置全局变量
                    LibPicDirecotryIntentInfo.setData(mFilterData);
                    LibPicDirectoryActivity.launch(LibPicSelectActivity.this, REQUEST_DIR_CODE);
                }
            }
        });
        mAdapter.setOnBindImageViewListener(new LibPicSelAdapter.BindImageViewListener() {
            @Override
            public void BindImageView(String path, ImageView iv) {
                if (LibPicSelConfig.getInstance().getBindListener() != null) {
                    LibPicSelConfig.getInstance().getBindListener().BindSmallImageView(path, iv);
                }
            }
        });
        mAdapter.setOnClickListener(new LibPicSelAdapter.OnClickListener() {
            //source 1图片 2视频。如果选择图片，则进入多选模式，若选择视频，则进入播放模式
            @Override
            public void click(List<LibPicInfo> data, int pos, int source) {
                if (data != null && data.size() != 0) {
                    List<String> result = new ArrayList<>();
                    List<LibPicInfo> local = LibPicCloneUtils.cloneObjectSer(data);
                    for (LibPicInfo cache : data) {
                        result.add(cache.getPath());
                    }
                    //赋值对象到内存中
                    LibPicSelIntentInfo.getInstance().setPicSelList(local);
                    LibPicSelIntentInfo.getInstance().setPicList(result);
                    LibPicBrowserActivity.launch(LibPicSelectActivity.this, pos, mLimit,
                            mCusVideoPlayUIMode, mParamsBuilder);
                }
            }

            @Override
            public void check() {
                //check box 事件
                updateSelCount();
            }

            @Override
            public void camera() {
                //询问用户，是拍照还是录制视频--dialog
                dealWithClickCamera();
            }

            @Override
            public void tipsMaxSel(int max) {
                LibPicToastUtils.toast(LibPicSelectActivity.this,
                        getString(R.string.lib_pic_activity_pic_select_sel_limit, max), Toast.LENGTH_SHORT);
            }

        });
        LibPicSelectManager.getInstance().setOnResultListener(new LibPicSelectManager.OnResultListener() {
            @Override
            public void Data(final List<LibPicInfo> result) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (mAdapter != null) {
                            mAdapter.setData(result);
                            //设置完数据，也要更新选中逻辑
                            updateSelCount();
                        }
                    }
                });
            }

            @Override
            public void FilterData(final Map<String, List<LibPicInfo>> filterMap) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        mFilterData = filterMap;
                    }
                });
            }
        });
        LibPicSelectManager.getInstance().init(this, new LibPicSelectApi.InitCallBack() {
            @Override
            public void NoPermission() {
                finish();
            }

            @Override
            public void Success() {
                //初始化成功，则加载数据
                LibPicSelectManager.getInstance().load(isShowGif, isShowVideo, mParamsBuilder);
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //选中的目录
        if (requestCode == REQUEST_DIR_CODE && resultCode == RESULT_OK) {
            String directory = data.getStringExtra("path");
            mTitle.setText(!TextUtils.isEmpty(directory) ? directory : "暂无标题");
            if (!TextUtils.isEmpty(directory) && mFilterData.get(directory) != null) {
                mAdapter.setData(mFilterData.get(directory));
            }
            updateSelCount();
        }
        //全屏页面，普通返回
        if (requestCode == LibPicIntentCode.BROWSER_CODE_REQUEST && resultCode == LibPicIntentCode.PIC_SEL_RES) {
            if (mAdapter != null) {
                mAdapter.setData(LibPicSelIntentInfo.getInstance().getPicSelList());
                updateSelCount();
            }
        }
        //全屏页面，确认返回
        if (requestCode == LibPicIntentCode.BROWSER_CODE_REQUEST && resultCode == LibPicIntentCode.BROWSER_CODE_RESULT_CONFIRM) {
            if (mAdapter != null) {
                //重新读取内存数据，并更新UI
                mAdapter.setData(LibPicSelIntentInfo.getInstance().getPicSelList());
                updateSelCount();
                //设置返回结果
                if (mAdapter != null) {
                    Intent result = new Intent();
                    result.putExtra(LibPicIntentCode.PIC_SEL_DATA_SELECT, (Serializable) mAdapter.getSelectInfo());
                    setResult(LibPicIntentCode.PIC_SEL_RES, result);
                }
                finish();
            }
        }
        //全屏页面，没有确定返回
        if (requestCode == LibPicIntentCode.BROWSER_CODE_REQUEST && resultCode == LibPicIntentCode.BROWSER_CODE_RESULT) {
            if (mAdapter != null) {
                mAdapter.setData(LibPicSelIntentInfo.getInstance().getPicSelList());
                updateSelCount();
            }
        }
        //全屏页面，预览模式返回
        if (requestCode == LibPicIntentCode.BROWSER_CODE_REQUEST && resultCode == LibPicIntentCode.BROWSER_CODE_RESULT_PREVIEW_CONFIRM) {
            if (mAdapter != null) {
                //对象应用操作
                List<LibPicInfo> previewData = LibPicSelIntentInfo.getInstance().getPicSelList();
                if (previewData != null && previewData.size() != 0) {
                    //数据转换
                    List<LibPicInfo> adapterOrgInfo = mAdapter.getPicInfo();
                    for (int i = 0; i < adapterOrgInfo.size(); i++) {
                        LibPicInfo adapterPicInfo = adapterOrgInfo.get(i);
                        for (LibPicInfo previewInfo : previewData) {
                            if (!TextUtils.isEmpty(previewInfo.getPath()) &&
                                    !TextUtils.isEmpty(adapterPicInfo.getPath()) &&
                                    previewInfo.getPath().equals(adapterPicInfo.getPath())) {
                                //同一个数据--更新选中状态
                                adapterPicInfo.setSelect(previewInfo.isSelect());
                            }
                        }
                    }
                    //更新视觉
                    mAdapter.notifyDataSetChanged();
                    updateSelCount();
                }
            }
        }
        //若是中间页面，直接finish
        if (requestCode == LibPicIntentCode.PIC_SEL_MID_REQ_CODE && resultCode == LibPicIntentCode.PIC_SEL_MID_RES_CODE) {
            finish();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (isFinishing()) {
            LibPicSelectManager.getInstance().release();
            if (mAdapter != null) {
                mAdapter.reomveBindImageViewListener();
                mAdapter.removeOnClickListener();
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    /**
     * 更新选中个数
     */
    private void updateSelCount() {
        if (mAdapter != null) {
            int selSize = mAdapter.getSelectInfo().size();
            mConfirm.setText(String.format(getResources().getString(R.string.lib_pic_pic_select_activity_checkbox_count), selSize, mLimit));
        }
    }

    //拍照or录像dialog

    /**
     * 普通dialog
     */
    private void dealWithClickCamera() {
        //0什么都能选 1图片 2视频 100相对
        int type = mParamsBuilder.getOnlySelOneType();
        if (type == 1) {
            takeCamera();
            return;
        } else if (type == 2) {
            PicSelMain.getInstance().recordVideo(LibPicSelectActivity.this, mParamsBuilder.getRecordVideoMaxDuration());
            return;
        }
        final AlertDialog.Builder alterDiaglog = new AlertDialog.Builder(LibPicSelectActivity.this);
        alterDiaglog.setTitle("请选择");//文字
        alterDiaglog.setMessage("拍照还是录像");//提示消息
        alterDiaglog.setPositiveButton("拍照", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                //拍照
                takeCamera();
            }
        });
        alterDiaglog.setNegativeButton("录像", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                //录像
                PicSelMain.getInstance().recordVideo(LibPicSelectActivity.this, mParamsBuilder.getRecordVideoMaxDuration());
            }
        });
        //显示
        alterDiaglog.show();
    }

    /**
     * 打开相机拍照
     */
    private void takeCamera() {
        switch (isCusCameraMode) {
            case 1:
                PicSelMain.getInstance().takeCamera(LibPicSelectActivity.this, 1, 0);
                break;
            case 2:
                LibPicDataBusManager.getInstance().takeCameraInnerCus(LibPicSelectActivity.this, 0);
                break;
            case 3:
                LibPicDataBusManager.getInstance().takeCameraOuterCus(LibPicSelectActivity.this, 0);
                break;
            default:
                break;
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            LibPicDataBusManager.getInstance().cancel();
        }
        return super.onKeyDown(keyCode, event);
    }
}
